<?php

namespace app\common\model;

use think\Model;
use think\Session;
use think\Validate;

/**
 * Created by PhpStorm.
 * Author: Masky
 * Date: 2017/11/1
 * Time: 16:20
 */
class Admin extends Model {
	
	const STATUS_CLOSE=0;
	const STATUS_OPEN=1;
	
	public static $status=[
		self::STATUS_CLOSE=>'未激活',
		self::STATUS_OPEN=>'已激活'
	];
	public function addAdmin($input){
		$validate=new Validate(['username'=>'require|unique:admin','password'=>'require']);
		$result=FALSE;
		if($validate->check($input)){
			$input['password']=$this->createPassword($input['username'],$input['password']);
			$input['created_at']=time();
			$input['status']=1;
			$result=$this->create($input);
			$result || $this->error="添加管理员失败";
		}else{
			$this->error=$validate->getError();
		}
		return $result;
	}
	public function editAdmin($input){
		$validate=new Validate(['id'=>'require']);
		$result=FALSE;
		if($validate->check($input)){
			if($input['password']){
				$input['password']=$this->createPassword($input['username'],$input['password']);
			}else{
				unset($input['password']);
			}
			unset($input['username']);
			$result=$this->save($input,['id'=>$input['id']]);
			$result || $this->error="编辑管理员失败";
		}else{
			$this->error=$validate->getError();
		}
		return $result;
	}
	public function getInfo($condition=[],$field='*',$order='id desc'){
		
		$result=$this->where($condition)->field($field)->order($order)->find();
		$result && $this->formatSelect($result);
		return $result;
	}
	
	public function formatSelect(&$data){
		$data['created_at_dis']=date("Y-m-d H:i:s",$data['created_at']);
		$data['status_dis']=self::$status[$data['status']];
	}
	public function getList($condition=[],$field='*',$order='id asc',$size=15){
		
		$result=$this->where($condition)->field($field)->order($order)->paginate($size,false,['query' =>input()]);
		if($result){
			foreach ($result as &$item){
				$this->formatSelect($item);
			}
		}
		return $result;
	}
	public function login($username,$password,$token=''){
		$info=$this->get(['username'=>$username]);
		$result=FALSE;
		if($info){
			if($info['status']==self::STATUS_CLOSE){
				$this->error="账号未激活";
			}else{
				if($info['password'] == $this->createPassword($username,$password)){
					Session::set('admin',$info);
					$this->save(['login_at'=>time()],['id'=>$info['id']]);
					$result=TRUE;
				}else{
					$this->error="密码错误";
				}
			}
		}else{
			$this->error="找不到用户";
		}
		return $result;
	}
	public function createPassword($username,$password){
		return md5(md5($username).$password);
	}
	public static function checkLogin(){
		return Session::has("admin")?TRUE:FALSE;
	}
}